package com.da.javatest.leetCode;

/**
 * @author chenlida
 * @date 2018/12/11 16:03
 * @description
 */
public class Code59 {
    public static void main(String[] args) {
        int[][] ints = new Code59().generateMatrix(4);
        System.out.println(ints);
    }

    public int[][] generateMatrix(int n) {
        if (n == 1) {
            return new int[][] {{1}};
        }
        int[][] result = new int[n][n];
        return getNumb(result, 1, n, 0, 0);
    }

    private int[][] getNumb(int[][] result, int flag, int n, int start, int level) {
        if ((n * n) == start) {
            return result;
        } else {
            if (flag == 1) {
                for (int i = level; i < n - level; i++) {
                    result[level][i] = ++start;
                }
                return getNumb(result, 2, n, start, level);
            } else if (flag == 2) {
                for (int i = level + 1; i < n - level; i++) {
                    result[i][n - level - 1] = ++start;
                }
                return getNumb(result, 3, n, start, level);
            } else if (flag == 3) {
                for (int i = n - level - 2; i >= level; i--) {
                    result[n - level - 1][i] = ++start;
                }
                return getNumb(result, 4, n, start, level);
            } else {
                for (int i = n - level - 2; i >= level + 1; i--) {
                    result[i][level] = ++start;
                }
                return getNumb(result, 1, n, start, level += 1);
            }
        }

    }
}
